//
// Created by ChenJi on 2021/4/13.
//

#include <tim.h>
#include "rtc_extern.h"
#include "Warner_Manager.h"
#include "TastekE16.h"
#include "lcd_extern.h"
#include "door_manager.h"
#include "data_center.h"
#include "interaction_handle.h"
#include "finger_sener.h"
#include "sound.h"

uint8_t door_state;
uint8_t warnerstate;

uint8_t isCertified;

uint8_t defeat_state;
uint8_t waiting_disable_defeat = 0;
uint8_t warning;
uint8_t waiting_for_lock_and_defeat;

void WarnerManagerInit() {
    defeat_state = 0;
}

void onConnected() {
    startSyncTimePlan();
    sendVerifyPocket();
    debug("[DEBUG]CONNECTED\n");
}

void onDisconnected() {
    stopSyncTimePlan();
    debug("[DEBUG]DISCONNECTED\n");
}

void onServerVerifyDone() {
    isCertified = 1;
    debug("[DEBUG]Server Verify Done，Init Done\n");

}

void onServerVerifyFailed() {
    debug("[DEBUG]Server Failed\n");
}

void onDefeat_Disable_Apply() {
    if (waiting_disable_defeat)return;
    verifyFinger();
    waiting_disable_defeat = 1;
    playSoundAsync(1);
}

void onDefeat_Enable_Apply() {
    debug("[DEBUG]Defeat Enabled\n");
    if (door_state) {
        waiting_for_lock_and_defeat = 1;
        playSoundAsync(2);
    } else {
        playSoundAsync(3);
        chenge_Defeat_state(1);
        defeat_state = 1;  //day state;
    }


}

void onVerifySuccess(uint16_t number, uint16_t score) {
    playSoundAsync(4);
    setFingerSensorData(3);
    waiting_disable_defeat = 0;
    debug("[DEBUG]Defeat Disabled\n");
    chenge_Defeat_state(0);
    defeat_state = 0; //standby
    if(warning){
        HAL_TIM_PWM_Stop(&htim2,TIM_CHANNEL_1);
    }
}

void onDoorClose() {
    setDoorIcon(1);
    LED_R_RESET;
    debug("[DEBUG]The Door Closed\n");
    door_state = 0;
    if(warning){
        return;
    }
    if (waiting_for_lock_and_defeat) {
        playSoundAsync(3);
        chenge_Defeat_state(1);
        defeat_state = 1;  //day state;
        waiting_for_lock_and_defeat = 0;
    }
}

void onDoorOpen() {
    setDoorIcon(0);
    LED_R_SET;
    debug("[DEBUG]The Door opened\n");
    door_state = 1;
    if(warning){
        return;
    }
    if (defeat_state == 1) {
        playSoundAsync(5);
        verifyFinger();
    }
}

void reloadMainInterfaceEvent(uint8_t *state) {
    *state = defeat_state;
}

void onRederFind(uint16_t distance, uint16_t single) {
    setMoveIcon(1);
    if (defeat_state) {
        warning = 1;
        HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
        playSoundAsync(6);
        if (waiting_disable_defeat)return;
        verifyFinger();
        waiting_disable_defeat = 1;
        addEvent(EVENT_TYPE_SETDEFEAT);
        sendEventToServer(8);
    }
}

void onRaderLeave(uint16_t distance, uint16_t single) {
    setMoveIcon(0);
}
uint8_t getDoorState(){
    return door_state;
}